#include "io_service_pool.h"

io_service_pool::io_service_pool( CLogModule* pLogModule )
	: m_next_io_service(0)
	, m_pLogModule(pLogModule)
{
	m_pLogModule->WriteLog(LOG_DEBUG,"io_service_pool construct.");
	m_nCoreNum = boost::thread::hardware_concurrency();
	for (unsigned int i = 0;i < m_nCoreNum;i++)
	{
		io_service_ptr ios(new boost::asio::io_service);
		io_service_work_ptr ios_work(new boost::asio::io_service::work(*ios));
		m_vec_io_service.push_back(ios);
		m_vec_io_service_work.push_back(ios_work);
	}
}

io_service_pool::~io_service_pool(void)
{
	m_pLogModule->WriteLog(LOG_DEBUG,"io_service_pool destruct.");
}

void io_service_pool::Run( void )
{
	m_pLogModule->WriteLog(LOG_DEBUG,"entry io_service_pool::Run.");
	std::vector<thread_ptr> vecThread;
	BOOST_FOREACH(io_service_ptr p,m_vec_io_service)
	{
		thread_ptr tp(new boost::thread(boost::bind(&boost::asio::io_service::run,p)));
		vecThread.push_back(tp);
	}
	BOOST_FOREACH(thread_ptr p,vecThread)
		p->join();
	m_pLogModule->WriteLog(LOG_DEBUG,"exit io_service_pool::Run.");
}

void io_service_pool::Stop( void )
{
	m_pLogModule->WriteLog(LOG_DEBUG,"entry io_service_pool::Stop.");
	BOOST_FOREACH(io_service_ptr p,m_vec_io_service)
		p->stop();
	m_pLogModule->WriteLog(LOG_DEBUG,"exit io_service_pool::Stop.");
}

boost::asio::io_service & io_service_pool::Get_io_service( void )
{
	m_pLogModule->WriteLog(LOG_DEBUG,"entry io_service_pool::Get_io_service.");
	return *m_vec_io_service[ ((m_next_io_service++) % m_nCoreNum) ];
	m_pLogModule->WriteLog(LOG_DEBUG,"exit io_service_pool::Get_io_service.");
}
